<template>
	<view class="page-container">
		<u-image :src="require('../../static/bg.png')" width="100%" height="100vh" mode="aspectFill"
			class="background-image"></u-image>
		<view class="questions">
			<view class="question">
				{{content}}
			</view>
			<view class="question">
				{{questionPrompt}}
			</view>
			<!-- 添加倒计时显示 -->
			<view class="conutdown" v-if="isCountingDown">
				剩余时间：{{formatTime(remainingTime)}}
			</view>

		</view>
		<view class="content">
			<u-button type="primary" size="large" @click="handleBeginInterview">{{btnText}}</u-button>

		</view>
	</view>
</template>

<script>
	import {
		getQuestions,
		genReport
	} from '@/api/answer/answer'
	export default {
		data() {
			return {
				questions: [],
				index: 0,
				//问题
				content: '请点击“开始面试”按钮开始答题',
				//问题提示
				questionPrompt: '',
				btnText: '开始面试',
				//录音管理器
				recorderManager: null,
				//录音文件地址
				recordFilePath: null,
				//计时器相关变量
				isCountingDown: false, //是否正在倒计时
				timer: null,
				remainingTime: 300 //剩余时间


			};
		},
		

		methods: {
			//根据面试记录加载面试问题

			async loadQuestions() {
				let recordId = uni.getStorageSync("interviewRecord")
				const res = await getQuestions(recordId);
				this.questions = res.data
			},
			//开始面试
			handleBeginInterview() {

				//==========录音的逻辑====================
				if (this.index == 0) {
					//开启下一次的录音
					this.btnText = "下一题"
					this.showQuestion(this.index);
					//开始录音
					this.recorderManager.start({
						duration: 300000,
						format: 'mp3'
					})
					//开始倒计时
					this.startCountdown()
					this.index++;
				} else {
					//结束上一次的录音
					this.recorderManager.stop()
					//停止倒计时
					this.stopCountdown()
				}

			},
			//==========展示题目====================
			showQuestion(index) {
				if (index < this.questions.length) {
					this.content = this.questions[this.index].content
					this.questionPrompt = this.questions[this.index].questionPrompt;
				}
			},
			//上传录音
			uploadRecord() {
				console.log(this.recordFilePath)
				uni.uploadFile({
					url: 'http://localhost:8080/interview/answer/handleAnswer',
					filePath: this.recordFilePath.file,
					name: 'file',
					formData: {
						questionId: this.recordFilePath.questionId
					},
					success: (res) => {
						console.log('res', res)
					}

				})


			},
			//格式化时间  （秒-->00:00）
			formatTime(seconds) {
				const mins = Math.floor(seconds / 60).toString().padStart(2, '0');
				const secs = (seconds % 60).toString().padStart(2, '0');
				return `${mins}:${secs}`;
			},
			// 开始倒计时
			startCountdown() {
				this.isCountingDown = true;
				this.timer = setInterval(() => {
					if (this.remainingTime > 0) {
						this.remainingTime--;
					} else {
						// 时间到，自动下一题
						this.handleTimeout();
					}
				}, 1000);
			},

			// 停止倒计时
			stopCountdown() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
					this.isCountingDown = false;
				}
			},
			// 处理超时
			handleTimeout() {
				this.stopCountdown();
				// 停止录音
				if (this.recordManager) {
					this.recordManager.stop();
				}
				// 自动切换到下一题
				if (this.index < this.questions.length) {
					this.index++;
					this.showQuestion(this.index);
					this.remainingTime = 300; // 重置为5分钟
					this.startCountdown();
				}
			}
			
			
		},
		onLoad() {
			this.loadQuestions()
			//获取录音对象
			this.recorderManager = uni.getRecorderManager();
			//录音结束   
			this.recorderManager.onStop((res) => {
				this.recordFilePath = {
					file: res.tempFilePath,
					questionId: this.questions[this.index - 1].id //结束的上一次录音，所以是this.index-1
				}
				//上传录音文件
				this.uploadRecord()
				//=========控制按钮显示的内容=======
				if (this.index > 0 && this.index < this.questions.length - 1) {
					this.btnText = '下一题'
				} else {
					this.btnText = '结束面试'
				}
				//=========展示当前题目=======
				this.showQuestion(this.index++)
				console.log(this.index)
				console.log(this.questions.length)
				//最后一次点击
				if (this.index > this.questions.length) {
					let recordId = uni.getStorageSync('interviewRecord');
					//异步请求生成评价
					genReport(recordId)
					//页面跳转
					uni.navigateTo({
						url: '/pages/interview/interview'
					})
				} else {
					//开启下一次的录音
					this.recorderManager.start({
						duration: 300000,
						format: 'mp3'
					})
					
					//开始新题目倒计时
					this.remainingTime=300;
					this.startCountdown()
				}
				if(this.index<this.questions.length){
					this.index++
				}	
			})
		
		},
		
		//页面加载完毕 停止计时
		onUnload() {
			this.stopCountdown()
		}
	}
</script>

<style lang="scss">
	.page-container {
		position: relative;
		width: 100%;
		height: 100vh;
	}

	.background-image {
		position: fixed;
		top: 0;
		left: 0;
		z-index: -1;
	}

	.content {
		position: fixed;
		bottom: 150rpx;
		left: 125rpx;
		z-index: 1;
		width: 500rpx;
	}

	.questions {
		position: fixed;
		z-index: 1;
		bottom: 400rpx;
		/* 增加与按钮的距离 */
		left: 50%;
		transform: translateX(-50%);
		width: 90%;
		max-width: 600rpx;
		background-color: rgba(255, 255, 255, 0.85);
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		
		 .countdown {
		      font-size: 28rpx;
		      color: #ff0000;
		      text-align: center;
		      margin-top: 20rpx;
		      font-weight: bold;
		    }
	}
	.question {
		font-size: 32rpx;
		line-height: 1.6;
		color: #333;
		margin-bottom: 20rpx;
		text-align: center;

		&:first-child {
			font-weight: bold;
			font-size: 36rpx;
			margin-bottom: 15rpx;
		}
	}
</style>